package com.ccnu.JobHub.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccnu.JobHub.common.util.Token;
import com.ccnu.JobHub.model.common.Result;
import com.ccnu.JobHub.model.database.*;
import com.ccnu.JobHub.model.request.*;
import com.ccnu.JobHub.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("post")
@CrossOrigin("*")
@Slf4j
public class PostController {

    private final PostService postService;
    private final ViewPostService viewPostService;
    private final StudentService studentService;
    private final CommentService commentService;
    private final StarRelationService starRelationService;
    private final CommentLikeService commentLikeService;
    private final PostLikeService postLikeService;
    private final PostTagService postTagService;

    /**
     * 构造函数
     * @param postService 帖子
     * @param viewPostService 升学帖
     * @param studentService 学生
     * @param commentService 评论
     * @param starRelationService 点赞关系
     * @param commentLikeService 评论点赞
     * @param postLikeService 帖子点赞
     */
    public PostController(PostService postService, ViewPostService viewPostService, StudentService studentService, CommentService commentService, StarRelationService starRelationService, CommentLikeService commentLikeService, PostLikeService postLikeService, PostTagService postTagService) {
        this.postService = postService;
        this.viewPostService = viewPostService;
        this.studentService = studentService;
        this.commentService = commentService;
        this.starRelationService = starRelationService;
        this.commentLikeService = commentLikeService;
        this.postLikeService = postLikeService;
        this.postTagService = postTagService;
    }

    /**
     *获取首页推荐帖子和个人主页帖子
     * @param pageRequest 输入页数和页面大小，实现分页
     * @return 返回一个列表的帖子内容
     */
    @GetMapping("recommendations")
    public Result recommendations(@RequestHeader("token") String token,@ModelAttribute PageRequest pageRequest,@RequestParam("flag") String flag){
        log.info("--------------------返回帖子列表请求--------------------");
        String studentId = Token.inspectOldToken(token);
        QueryWrapper<Post> postQueryWrapper;
        if (Objects.equals(flag, "0")){
            postQueryWrapper = new QueryWrapper<Post>()
                    .orderByDesc("updated_at");
        }
        else{
            postQueryWrapper = new QueryWrapper<Post>()
                    .eq("student_id",studentId)
                    .orderByDesc("updated_at");
        }
        Page<Post> page = Page.of(pageRequest.getPage(),pageRequest.getPageSize());
        Page<Post> p = postService.page(page,postQueryWrapper);
        List<Post> posts = p.getRecords();
        if (posts == null || posts.isEmpty()){
            return Result.error("数据库里没有帖子");
        }

        for (Post post : posts){
            Student student = studentService.getById(post.getStudentId());
            post.setNickname(student.getNickname());
//                post.setAvatar(student.getAvatar()); 因为现在使用接口来获取头像了，而不是本地url了
        }
        return Result.success("查看帖子成功", posts);
    }

    /**
     *获得某id的帖子内容，用于转发贴的内容
     * @param PostId 帖子对应的id
     * @return 返回对应帖子的内容
     */
    @GetMapping("getPostById")
    public Result getById(@RequestParam("postId") String PostId){
        log.info("根据帖子id查看内容请求");
        Post post = postService.getById(PostId);
        if (post==null){
            return Result.error("不存在该帖子");
        }
        Student student = studentService.getById(post.getStudentId());
        post.setNickname(student.getNickname());
//        post.setAvatar(student.getAvatar()); 因为现在使用接口来获取头像了，而不是本地url了
        return Result.success("返回对应帖子成功", post);
    }

    /**
     * 查看评论
     * @param postId 评论id
     * @return 返回一个评论列表
     */
    @GetMapping("comments")
    public Result comments(@RequestParam("postId") String postId){
        log.info("--------------------返回评论列表请求--------------------");
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<Comment>()
                .eq("post_id",postId)
                .orderByAsc("created_at");

        List<Comment> comments = commentService.list(commentQueryWrapper);
        Map<Long, Comment> commentMap = new HashMap<>();
        List<Comment> result = new ArrayList<>();
        for (Comment comment : comments) {
            long commentId = comment.getCommentId();
            Long parentId = comment.getParentCommentId();
            Student student = studentService.getById(comment.getStudentId());
            comment.setNickname(student.getNickname());
//            comment.setAvatar(student.getAvatar());
            // 如果父评论字段为 null，将该评论添加到结果列表中
            if (parentId == null) {
                result.add(comment);
            } else {
                // 如果父评论字段不为 null，将该评论添加到对应父评论的子评论列表中
                comment.setReplyName(studentService.getById(commentService.getById(parentId).getStudentId()).getNickname());
                Comment parentComment = commentMap.get(parentId);
                List<Comment> sonComments = parentComment.getSonComments();
                if (sonComments == null) {
                    sonComments = new ArrayList<>();
                }
                sonComments.add(comment);
                parentComment.setSonComments(sonComments);
            }
            commentMap.put(commentId, comment);
        }
        return Result.success("查看评论成功", result);
    }

    /**
     * 获取评论条数
     * @param postId 对应的帖子id
     * @return 一个Result结果
     */
    @GetMapping("commentsCount")
    public Result commentsCount(@RequestParam("postId") String postId){
        log.info("--------------------获取评论条数请求--------------------");
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<Comment>()
                .eq("post_id",postId);
        long count = commentService.count(commentQueryWrapper);
        return Result.success("获取评论条数成功",count);
    }

    /**
     * 获取评论条数
     * @param studentId 学生学号
     * @return 一个Result结果
     */
    @GetMapping("postsCount")
    public Result postsCount(@RequestParam("studentId") String studentId){
        log.info("--------------------获取帖子条数请求--------------------");
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<Post>()
                .eq("student_id",studentId);
        long count = postService.count(postQueryWrapper);
        return Result.success("获取帖子条数成功",count);
    }

    /**
     * 帖子点赞点踩
     * @param postIsLikeRequest 可以包含是帖子还是评论，然后是点赞还是点踩，然后是取消还是正常点
     * @return 返回一个成功的消息
     */
    @PutMapping("postIsLike")
    public Result postIsLike(@RequestHeader("token") String token,@RequestBody PostIsLikeRequest postIsLikeRequest){
        log.info("--------------------帖子点赞点踩请求--------------------");
        String studentId = Token.inspectOldToken(token);
        QueryWrapper<PostLike> postLikeQueryWrapper = new QueryWrapper<PostLike>()
                .eq("student_id",studentId)
                .eq("post_id",postIsLikeRequest.getPostId());
        PostLike postLike = postLikeService.getOne(postLikeQueryWrapper);
        if (postLike == null){
            PostLike postLike1 = new PostLike();
            postLike1.setPostId(postIsLikeRequest.getPostId());
            postLike1.setStudentId(Long.valueOf(studentId));
            postLike1.setStatus(postIsLikeRequest.getStatue());
            postLikeService.save(postLike1);
            if(postIsLikeRequest.getStatue().equals(1)){
                postLike(postIsLikeRequest.getPostId(), "1");
            }
            else if (postIsLikeRequest.getStatue().equals(-1)){
                postDislike(postIsLikeRequest.getPostId(), "1");
            }
            else Result.error("已经是无状态了");

            return Result.success("点赞/点踩成功");
        }
        if (postLike.getStatus().equals(0)){
            if(postIsLikeRequest.getStatue().equals(1)){
                postLike(postIsLikeRequest.getPostId(), "1");
            }
            else if (postIsLikeRequest.getStatue().equals(-1)){
                postDislike(postIsLikeRequest.getPostId(), "1");
            }
            else Result.error("已经是无状态了");
        }
        else if (postLike.getStatus().equals(1)){
            if (postIsLikeRequest.getStatue().equals(0)){
                postLike(postIsLikeRequest.getPostId(),"-1");
            }
            else if (postIsLikeRequest.getStatue().equals(-1)){
                postLike(postIsLikeRequest.getPostId(),"-1");
                postDislike(postIsLikeRequest.getPostId(),"1");
            }
            else Result.error("已经点过赞了");
        }
        else {
            if (postIsLikeRequest.getStatue().equals(0)){
                postDislike(postIsLikeRequest.getPostId(),"-1");
            }
            else if (postIsLikeRequest.getStatue().equals(1)){
                postLike(postIsLikeRequest.getPostId(),"1");
                postDislike(postIsLikeRequest.getPostId(),"-1");
            }
            else Result.error("已经点过踩了");
        }
        postLike.setStatus(postIsLikeRequest.getStatue());
        postLikeService.saveOrUpdate(postLike);
        return Result.success("点赞/点踩成功");
    }    /**

     * 评论点赞点踩
     * @param commentIsLikeRequest 包含一个评论id，以及点赞之后的状态
     * @return 返回一个成功的消息
     */
    @PutMapping("commentIsLike")
    public Result commentIsLike(@RequestHeader("token") String token,@RequestBody CommentIsLikeRequest commentIsLikeRequest){
        log.info("--------------------评论点赞点踩请求--------------------");
        String studentId = Token.inspectOldToken(token);
        QueryWrapper<CommentLike> commentLikeQueryWrapper = new QueryWrapper<CommentLike>()
                .eq("student_id",studentId)
                .eq("comment_id",commentIsLikeRequest.getCommentId());
        CommentLike commentLike = commentLikeService.getOne(commentLikeQueryWrapper);
        if (commentLike == null){
            CommentLike commentLike1 = new CommentLike();
            commentLike1.setCommentId(commentIsLikeRequest.getCommentId());
            commentLike1.setStudentId(Long.valueOf(studentId));
            commentLike1.setStatus(commentIsLikeRequest.getStatue());
            commentLikeService.save(commentLike1);
            if(commentIsLikeRequest.getStatue().equals(1)){
                commentLike(commentIsLikeRequest.getCommentId(), "1");
            }
            else if (commentIsLikeRequest.getStatue().equals(-1)){
                commentDislike(commentIsLikeRequest.getCommentId(), "1");
            }
            else Result.error("已经是无状态了");
            return Result.success("点赞/点踩成功");
        }
        if (commentLike.getStatus().equals(0)){
            if(commentIsLikeRequest.getStatue().equals(1)){
                commentLike(commentIsLikeRequest.getCommentId(), "1");
            }
            else if (commentIsLikeRequest.getStatue().equals(-1)){
                commentDislike(commentIsLikeRequest.getCommentId(), "1");
            }
            else Result.error("已经是无状态了");
        }
        else if (commentLike.getStatus().equals(1)){
            if (commentIsLikeRequest.getStatue().equals(0)){
                commentLike(commentIsLikeRequest.getCommentId(),"-1");
            }
            else if (commentIsLikeRequest.getStatue().equals(-1)){
                commentLike(commentIsLikeRequest.getCommentId(),"-1");
                commentDislike(commentIsLikeRequest.getCommentId(),"1");
            }
            else Result.error("已经点过赞了");
        }
        else {
            if (commentIsLikeRequest.getStatue().equals(0)){
                commentDislike(commentIsLikeRequest.getCommentId(),"-1");
            }
            else if (commentIsLikeRequest.getStatue().equals(1)){
                commentLike(commentIsLikeRequest.getCommentId(),"1");
                commentDislike(commentIsLikeRequest.getCommentId(),"-1");
            }
            else Result.error("已经点过踩了");
        }
        commentLike.setStatus(commentIsLikeRequest.getStatue());
        commentLikeService.saveOrUpdate(commentLike);
        return Result.success("点赞/点踩成功");
    }

    private void postLike(Long postId, String  a) {
        UpdateWrapper<Post> postUpdateWrapper = new UpdateWrapper<Post>()
                .eq("post_id", postId)
                .setSql("like_num = like_num + "+a);
        postService.update(postUpdateWrapper);
    }
    private void postDislike(Long postId, String  a) {
        UpdateWrapper<Post> postUpdateWrapper = new UpdateWrapper<Post>()
                .eq("post_id", postId)
                .setSql("dislike = dislike + "+a);
        postService.update(postUpdateWrapper);
    }
    private void commentLike(Long commentId, String  a) {
        UpdateWrapper<Comment> commentUpdateWrapper = new UpdateWrapper<Comment>()
                .eq("comment_id", commentId)
                .setSql("like_num = like_num + "+a);
        commentService.update(commentUpdateWrapper);
    }
    private void commentDislike(Long commentId, String  a) {
        UpdateWrapper<Comment> commentUpdateWrapper = new UpdateWrapper<Comment>()
                .eq("comment_id", commentId)
                .setSql("dislike = dislike + "+a);
        commentService.update(commentUpdateWrapper);
    }

    /**
     * 给帖子底下添加评论
     * @param token 放在请求头，用来验证和获取对应的学生id
     * @param newCommentRequest 这里是评论的一些内容
     * @return 成功添加
     */
    @PostMapping("newComment")
    public Result newComment(@RequestHeader("token") String token ,@RequestBody NewCommentRequest newCommentRequest){
        log.info("--------------------添加评论请求--------------------");
        String studentId = Token.inspectOldToken(token);
        LocalDateTime currentTime = LocalDateTime.now();
        Comment comment = new Comment();
        comment.setPostId(newCommentRequest.getPostId());
        comment.setStudentId(Long.valueOf(studentId));
        comment.setContent(newCommentRequest.getContent());
        comment.setCreatedAt(Timestamp.valueOf(currentTime));
        commentService.save(comment);
        return Result.success("添加评论成功",comment);
    }

    /**
     * 给评论添加一条回复的评论
     * @param token 放在请求头，用来验证和获取对应的学生id
     * @param newCommentRequest 这里是评论的一些内容
     * @return 成功添加
     */
    @PostMapping("comment/newComment")
    public Result comment_newComment(@RequestHeader("token") String token ,@RequestBody NewCommentRequest2 newCommentRequest){
        log.info("--------------------添加回复的评论请求--------------------");
        String studentId = Token.inspectOldToken(token);
        LocalDateTime currentTime = LocalDateTime.now();
        Comment comment = new Comment();
        Comment comment1 = commentService.getById(newCommentRequest.getCommentId());
        comment.setPostId(comment1.getPostId());
        if (comment1.getParentCommentId()!=null){
            comment.setParentCommentId(comment1.getParentCommentId());
        }
        else {
            comment.setParentCommentId(newCommentRequest.getCommentId());
        }
        comment.setStudentId(Long.valueOf(studentId));
        comment.setContent(newCommentRequest.getContent());
        comment.setCreatedAt(Timestamp.valueOf(currentTime));
        commentService.save(comment);
        return Result.success("添加评论成功",comment);
    }

    /**
     * 用来转发喜欢的帖子到自己的主页里面
     * @param token 放在请求头，用来验证和获取对应的学生id
     * @param shareRequest 转发贴的一些内容
     * @return 返回成功添加
     */
    @PostMapping("share")
    public Result share(@RequestHeader("token") String token ,@RequestBody NewCommentRequest shareRequest){
        log.info("--------------------转发帖子请求--------------------");
        String studentId = Token.inspectOldToken(token);
        Post post = new Post();
        Post post1 = postService.getById(shareRequest.getPostId());
        if (post1.getIsShare() == 0){
            post.setSharePostId(shareRequest.getPostId());
        }
        else {
            post.setSharePostId(post1.getSharePostId());
        }
        LocalDateTime currentTime = LocalDateTime.now();
        post.setContent(shareRequest.getContent());
        post.setCreatedAt(Timestamp.valueOf(currentTime));
        post.setUpdatedAt(Timestamp.valueOf(currentTime));
        post.setIsShare(1);
        post.setTitle("转发贴");
        post.setStatus(0);
        post.setStudentId(Long.valueOf(studentId));
        postService.save(post);
        return Result.success("转发帖子成功");
    }

    /**
     * 显示关注的人的贴子
     * @param token token令牌
     * @param pageRequest 分页的内容
     * @return Result结果
     */
    @GetMapping("followPost")
    public Result followPost(@RequestHeader("token") String token,@ModelAttribute PageRequest pageRequest){
        log.info("--------------------显示关注的帖子请求--------------------");
        String studentId = Token.inspectOldToken(token);

        QueryWrapper<StarRelation> starRelationQueryWrapper = new QueryWrapper<StarRelation>()
                .eq("student_id",studentId)
                .select("star_student_id");
        List<Integer> starRelations = starRelationService.listObjs(starRelationQueryWrapper,obj -> (Integer) obj);
        if (starRelations==null || starRelations.isEmpty()){
            return Result.error("您当前无关注用户");
        }
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<Post>()
                .orderByDesc("updated_at")
                .in("student_id",starRelations);
        Page<Post> page = Page.of(pageRequest.getPage(),pageRequest.getPageSize());
        List<Post> posts = postService.list(page,postQueryWrapper);
        for (Post post : posts){
            Student student = studentService.getById(post.getStudentId());
            post.setNickname(student.getNickname());
//            post.setAvatar(student.getAvatar()); 因为现在使用接口来获取头像了，而不是本地url了
        }
        return Result.success("显示关注的帖子成功",posts);
    }

    /**
     * 显示点赞点踩状态请求
     * @param token token令牌
     * @param type 类型
     * @return Result结果
     */
    @GetMapping("showLikeStatus")
    public Result showLikeStatus (@RequestHeader("token") String token,@RequestParam("type")String type, @RequestParam("id")String id){
        log.info("--------------------显示点赞点踩状态请求--------------------");
        String studentId = Token.inspectOldToken(token);
        if (type.equals("post")){
            QueryWrapper<PostLike> postLikeQueryWrapper = new QueryWrapper<PostLike>()
                    .eq("student_id",studentId)
                    .eq("post_id",id);
            PostLike postLike = postLikeService.getOne(postLikeQueryWrapper);
            if(postLike == null){
                return Result.success("成功显示点赞点踩状态",0);
            }
            return Result.success("成功显示点赞点踩状态",postLike.getStatus());
        }
        else {
            QueryWrapper<CommentLike> commentLikeQueryWrapper = new QueryWrapper<CommentLike>()
                    .eq("student_id",studentId)
                    .eq("comment_id",id);
            CommentLike commentLike = commentLikeService.getOne(commentLikeQueryWrapper);
            if(commentLike == null){
                return Result.success("成功显示点赞点踩状态",0);
            }
            return Result.success("成功显示点赞点踩状态",commentLike.getStatus());
        }
    }

    /**
     * 删除帖子
     * @param postId1 帖子id
     * @return 一个Result结果
     */
    @DeleteMapping("deletePost")
    public Result deletePost(@RequestBody Map<String,Object> postId1){
        log.info("--------------------删除帖子请求--------------------");
        Long postId = (Long) postId1.get("postId");
        boolean result = postService.removeById(postId);
        if (result){
            return Result.success("删除帖子成功");

        }
        else {
            return Result.error("表中无对应帖子");
        }
    }

    /**
     * 搜索帖子
     * @param page 当前页数
     * @param pageSize 页面大小
     * @param search 搜索内容
     * @return 一个Result结果
     */
    @GetMapping("searchPost")
    public Result searchPost(@RequestParam("page") Integer page,@RequestParam("pageSize") Integer pageSize,@RequestParam("search") String search,@RequestParam("type") String type) {
        log.info("--------------------搜索帖子请求--------------------");
        List<ViewPost> posts;
        if (type.equals("Enrollment")) {
            posts = viewPostService.searchEnrollmentPost(search, page, pageSize);
        }
        else {
            posts = viewPostService.searchJobPost(search, page, pageSize);
        }
        if (posts == null || posts.isEmpty()) {
            return Result.error("无相关帖子");
        }
        else return Result.success("搜索帖子成功", posts);
    }

    @PostMapping("newPost")
    public Result newPost(@RequestHeader("token") String token,@RequestBody NewPostRequest newPostRequest){
        log.info("--------------------发布帖子请求--------------------");
        String studentId = Token.inspectOldToken(token);
        if(newPostRequest.getTags().contains(2) && studentService.getById(studentId).getAuthority().equals(0)){
            return Result.error("无发帖权限");
        }
        Post post = new Post();
        post.setStudentId(Long.valueOf(studentId));
        post.setTitle(newPostRequest.getTitle());
        post.setContent(newPostRequest.getContent());
        post.setStatus(0);
        post.setIsShare(0);
        post.setSharePostId((long) -1);
        LocalDateTime currentTime = LocalDateTime.now();
        post.setCreatedAt(Timestamp.valueOf(currentTime));
        post.setUpdatedAt(Timestamp.valueOf(currentTime));
        try {
            postService.save(post);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error("数据库错误");
        }
        for (Integer tag: newPostRequest.getTags()){
            PostTag postTag = new PostTag();
            postTag.setTagId(tag);
            postTag.setPostId(post.getPostId());

            try {
                postTagService.save(postTag);
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("数据库错误");
            }
        }
        post.setNickname(studentService.getById(studentId).getNickname());
        return Result.success("成功发布帖子，等待审核中",post);
    }

    /**
     * 根据学生id显示帖子
     * @param studentId 学生id
     * @return 一个Result结果
     */
    @GetMapping("showOtherPosts")
    public Result showOtherPosts(@RequestParam("studentId") String studentId){
        log.info("--------------------根据学生id显示帖子请求--------------------");
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<Post>()
                .eq("student_id",studentId)
                .eq("status",1);
        List<Post> posts = postService.list(postQueryWrapper);
        if (posts.isEmpty()){
            return Result.error("该用户还未发帖");
        }
        for (Post post: posts){
            Student student;
            try {
                student = studentService.getById(post.getStudentId());
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("数据库错误");
            }
            post.setNickname(student.getNickname());
        }
        return Result.success("成功获得帖子",posts);
    }

    /**
     * 显示待审核帖子
     * @return 一个Result结果
     */
    @GetMapping("showPendingPost")
    public Result showPendingPost(){
        log.info("--------------------显示待审核帖子请求--------------------");
        QueryWrapper<Post> postQueryWrapper = new QueryWrapper<Post>()
                .eq("status",0);
       List<Post> posts = postService.list(postQueryWrapper);
       if (posts.isEmpty()){
           return Result.error("当前无待审核帖子");
       }
       for (Post post : posts){
           post.setNickname(studentService.getById(post.getStudentId()).getNickname());
       }
       return Result.success("显示待审核帖子", posts);
    }
}
